package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"xinduobang/stock/utils"

	//"context"
	"xinduobang/stock/common/fisherrors"
	"xinduobang/stock/core/timeout"
)

//func TimeoutMiddleware() gin.HandlerFunc {
//	timeout := 1 * time.Millisecond
//	return func(c *gin.Context) {
//		ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
//		defer cancel()
//
//		c.Request = c.Request.WithContext(ctx)
//		c.Next()
//
//		if ctx.Err() == context.DeadlineExceeded {
//			c.AbortWithStatusJSON(http.StatusOK, gin.H{
//				"code": fisherrors.CODE_TIMEOUT,
//				"msg":  "Request timeout",
//				"data": map[string]string{},
//			})
//		}
//	}
//}

func TimeoutMiddleware() gin.HandlerFunc {
	return timeout.New(
		timeout.WithTimeout(8000*time.Millisecond),
		timeout.WithHandler(func(c *gin.Context) {
			c.Next()
		}),
		timeout.WithResponse(func(c *gin.Context) {
			utils.Error(c, "Request 超时了", map[string]interface{}{
				"method":     c.Request.Method,
				"path":       c.Request.URL.Path,
				"status":     c.Writer.Status(),
				"ip":         c.ClientIP(),
				"user_agent": c.Request.UserAgent(),
			})
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code": fisherrors.CodeTimeout,
				"msg":  "Request timeout",
				"data": map[string]string{},
			})
			//c.String(http.StatusOK, http.StatusText(http.StatusRequestTimeout))
		}),
	)
}
